<template>
	<div>
		<el-form ref="ruleForm" class="meal_form" :model="meal_list" :rules="rules" label-width="200px">
			<el-form-item label="租期设置:" prop="pact_type" style="line-height: 40px;">
				<el-checkbox-group v-model="submitForm.checkedLease">
					<el-checkbox v-for="val in leaseOptions" :key="val" :label="val" :disabled="enAble">{{ val }}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item v-for="(domain, index) in submitForm.domains" :label="'套餐颜色'" :key="domain.key"
				:prop="'domains.' + index + '.value'">
				<div class="flex">
					<el-input v-model="domain.color" style="margin-right: 20px;" />
					<crop-upload ref="coverUpload" show-type="photo" :fixScale="true" :is-square="true" :always-crop="true"
						:fixedBox="false" :init-val="domain.img" :type="meal" wrapper-width="120px" wrapper-height="120px"
						:photo-width="120" :photo-height="120" :autoCropWidth="150" :autoCropHeight="150" cropperWidth="400px"
						cropperHeight="400px" dialogWidth="600px" :min-width="150" :min-height="150" :enlarge="5" :params="index"
						@setVal="(val) => setUrl(index, val)">
					</crop-upload>
						<el-button v-show="index==0" @click.prevent="removeDomain(domain)" style="margin-left: 20px;height: 40px;">删除</el-button>
						<el-button @click="addDomain" v-show="index==0" style="height: 40px;">新增颜色</el-button>
				</div>
			</el-form-item>
			<el-form-item style="margin-top: 40px;" v-for="(domain, index) in submitForm.spec" :label="'规格套餐'" :key="domain.img"
				:prop="'domains.' + index + '.value'">
				<div class="flex align-center">
					规 格：<el-input v-model="domain.name" />
					官网价：<el-input v-model="domain.price" />
					费 率：<el-input v-model="domain.feee" />
						<el-button v-show="index==0" @click.prevent="removeSpec(domain)" style="margin-left: 20px;">删除</el-button>
						<el-button @click="addSpec" v-show="index==0">新增规格</el-button>
				</div>
			</el-form-item>
			<el-form-item>
				<el-button icon="el-icon-plus" size="small" type="primary" class="add_btn" style="margin-left: 0;"
					@click="createMeal">生成套餐</el-button>
				<el-button icon="el-icon-edit" size="small" type="primary" class="add_btn" style="margin-left: 10px;"
					@click="updateMeal">修改套餐</el-button>
			</el-form-item>
		</el-form>
		<div class="fix-footer-btns">
			<div>
				<template v-if="$route.name === 'goodsAdd'">
					<el-button size="small" class="blue_border" @click="returnTab">返回</el-button>
					<el-button v-if="draftId" size="small" class="blue_border" @click="addMeal(true)">保存套餐</el-button>
					<el-button v-if="!draftId && $hasMethod('#publish')" size="small" type="warning"
						@click="addMeal(true)">发布商品</el-button>
				</template>
			</div>
		</div>
	</div>
</template>
  
<script>
import cropUpload from '@/components/cropUpload'
import { addSetmeal, getGoodsSetmealInfo, editGoodsSetmeal, getGoodsInfo } from '@/api/goods'

// const leaseOptions = ['1天', '7天', '15天', '30天', '90天', '120天', '180天', '270天', '365天']
export default {
	components: { cropUpload },
	props: ['currentMeal', 'editId', 'draftId'],
	data() {
		return {
			submitForm: {
				checkedLease: ['365天'],
				domains: [{
					color: '',
					img: ''
				}],
				spec:[{
					name:'',
					price:'',
					fee:''
				}]
			},
			leaseOptions:['1天', '7天', '15天', '30天', '90天', '120天', '180天', '270天', '365天']
		}
	},
	watch: {
		currentMeal(val, oldVal) {
			this.getData()
		}
	},
	computed: {
		pactType: function () {
			return false
		}
	},
	mounted() {
		this.init()
		this.$nextTick(() => {
			if (this.$route.name === 'goodsMeal') {
				this.goodsId = this.$route.params.goodsId
				if (this.editId) {
					this.getInfo()
				} else {
					this.rentType = this.$route.params.pact_type
				}
			} else {
				this.rentType = JSON.parse(sessionStorage.getItem('baseInfo')) ? JSON.parse(sessionStorage.getItem('baseInfo')).formData.pact_type : 0
				this.goodsId = sessionStorage.getItem('goodsId') || ''
				this.getData()
			}
		})
	},
	beforeDestroy() {
		if (this.$route.name === 'goodsAdd') {
			this.saveStorage(this.currentMeal)
		}
	},
	methods: {
		// 生成套餐
		createMeal() {
			console.log(this.submitForm);

		},
		// 返回上一标签
		returnTab() {
			this.$emit('setTab', 'base')
		},
		setUrl(key, value) {
			this.submitForm.domains[key].img = value[0]
		},
		addDomain() {
			this.submitForm.domains.push({
				color: '',
				img: ''
			})
		},
		addSpec(){
			this.submitForm.spec.push({
				name:'',
				price:'',
				fee:''
			})
		},
		removeDomain(item) {
			if (this.submitForm.domains.length == 1) {
				this.$message({
					message: '商品至少存在一种颜色',
					type: 'warning'
				})
			} else {
				var index = this.submitForm.domains.indexOf(item)
				if (index !== -1) {
					this.submitForm.domains.splice(index, 1)
				}
			}
		},
		removeSpec(item){
			if (this.submitForm.spec.length == 1) {
				this.$message({
					message: '商品至少存在一种套餐规格',
					type: 'warning'
				})
			} else {
				var index = this.submitForm.spec.indexOf(item)
				if (index !== -1) {
					this.submitForm.spec.splice(index, 1)
				}
			}
		},
		// 保存草稿
		saveToDraft() {
			if (!this.goodsId) {
				this.$message({
					message: '请先提交商品基础信息',
					type: 'warning'
				})
				return
			}
			const params = { goods_id: this.goodsId, spec: this.meal_list, colorList: this.colorList, specList: this.specList, mealList: this.checkedLease, status: this.status, operation_type: 1 }
			if (params.setmeal_id) {
				params.mealList = Array.from(new Set(this.submitForm.checkedLease))
				// 存在套餐id，编辑套餐
				editGoodsSetmeal(params).then(res => {
					this.saveStorage()
					this.$message({
						message: '保存成功',
						type: 'success'
					})
				})
			} else {
				// 不存在套餐id，添加套餐
				delete params.setmeal_id
				addSetmeal(params).then(res => {
					this.meal_list.setmeal_id = res.setmeal_id
					this.saveStorage()
					this.$message({
						message: '保存成功',
						type: 'success'
					})
				})
			}
		},
		init() {
			this.is_show = true
			this.is_setmeal = true
			this.enAble = false
			this.isRead = false
			this.goods_id = sessionStorage.getItem('goodsId')
			getGoodsInfo(this.goods_id).then(res => {
				// console.log('setMealInfo=>', res)
				if (res.setmeal.length === 0) {

				} else {
					res.meal.forEach((item) => {
						this.setItemIdList.push(item.setmeal_id)
					})
					if (this.draftId) {
						this.submitForm.checkedLease = []
						this.is_meal = true
						this.is_show = false
						this.is_setmeal = false
						this.enAble = true
						this.isRead = true
						for (const key in this.submitForm) {

							if (key === 'checkedLease') {
								this.checkedLease = []
								if (res.setmeal[0].pect_type[1] === undefined) {
									res.setmeal[0].pect_type[2].forEach(item => {
										this.submitForm.checkedLease.push(item.lease_name)
									})
									this.submitForm.checkedLease = Array.from(new Set(this.submitForm.checkedLease))
								} else {
									res.setmeal[0].pect_type[1].forEach(item => {
										this.submitForm.checkedLease.push(item.lease_name)
									})
									this.submitForm.checkedLease = Array.from(new Set(this.submitForm.checkedLease))
								}

							} else if (key === 'meal_list') {
								// this.submitForm.meal_list = this.createMeal()
							} else if (key === 'title') {
								this.submitForm.title = res.setmeal[0].title
							} else if (key === 'price') {
								const meList = res.setmeal
								this.meal_list = meList
								this.submitForm.price = meList
							} else if (key === 'colorOfSpec') {
								const color = []
								const spec = []
								if (res.attr.length !== 0) {
									res.attr.forEach(item => {
										if (item.type === 1) {
											color.push({
												color: item.value
											})
										} else if (item.type === 2) {
											spec.push({
												spec: item.value
											})
										}
									})
								} else {
									res.meal.forEach(item => {
										color.push({
											color: item.color
										})
										spec.push({
											spec: item.spec
										})
									})
								}
								this.colorList = color.filter((element, index, self) => {
									return self.findIndex(x => x.color === element.color) === index
								})
								this.specList = spec.filter((element, index, self) => {
									return self.findIndex(x => x.spec === element.spec) === index
								})
							}
						}
					}
				}
				sessionStorage.setItem('pactType', res.pact_type)
				this.pect_type = this.draftId ? res.pact_type : sessionStorage.getItem('baseOfPactType').split(',')
				this.goods_name = res.title
			})
		},
		getData() {
			this.meal_list = {
				setmeal_id: '',
				title: '',
				lease_set: 1,
				quantity: 0,
				is_buy_out: 1,
				price: ''
			}
			if (sessionStorage.getItem('mealInfo')) {
				const list = JSON.parse(sessionStorage.getItem('mealInfo'))
				if (list[this.currentMeal - 1]) {
					const data = list[this.currentMeal - 1]
					this.meal_list = { ...data.formData }
					this.monthList = [...data.monthList]
					this.dayList = [...data.dayList]
					this.customList = [...data.customList]
				}
				this.status = parseInt(sessionStorage.getItem('goodsStatus'))
			}
		},
		saveStorage(index) {
			const params = { formData: this.meal_list, monthList: this.monthList, dayList: this.dayList, customList: this.customList }
			const list = sessionStorage.getItem('mealInfo') ? JSON.parse(sessionStorage.getItem('mealInfo')) : []
			list[index - 1] = { ...params }
			sessionStorage.setItem('mealInfo', JSON.stringify(list))
			sessionStorage.setItem('goodsStatus', this.status)
		},
		getInfo() {
			getGoodsSetmealInfo(this.editId).then(res => {
				for (const key in this.meal_list) {
					if (key === 'setmeal_id') {
						this.meal_list[key] = res.id
					} else {
						this.meal_list[key] = res[key]
					}
				}
				this.rentType = res.pact_type
				this.status = res.goods_status
			})
		}
	}
}
</script>
  
<style lang="scss" scoped>
.meal_form {
	padding: 30px 120px 30px 0;
}

.set_wrap {
	padding: 20px;
	background-color: #fafafa;
}

.set_form {
	border-bottom: 1px dashed #cdcdcd;
	margin-bottom: 16px;

	.item {
		margin-bottom: 16px;
	}

	.el-select,
	.el-input {
		width: 160px;
	}
}

label {
	margin-right: 14px;
}

.required-icon {
	margin-right: 3px;
}

.add_btn {
	// margin-left: 50px;
	margin-left: 10px;
}

.suffix {
	background: #f5f5f5;
	border: 1px solid #dcdfe6;
	border-radius: 0 4px 4px 0;
	height: 40px;
	display: inline-block;
	padding: 0 8px;
	box-sizing: border-box;
	border-left: none;
	line-height: 38px;
}

.suffix.before {
	border-left: 1px solid #dcdfe6;
	border-right: none;
	border-radius: 4px 0 0 4px;
}

.day_form {
	/deep/.el-input__inner {
		border-radius: 4px 0 0 4px;
	}
}

.custom_form {
	margin-top: 8px;
	margin-bottom: 8px;

	/deep/.el-input__inner,
	.el-select {
		border-radius: 0 4px 4px 0;
	}

	.no_border /deep/.el-input__inner {
		border-radius: 0;
	}

	&>div {
		margin-right: 10px;
		margin-bottom: 10px;
	}
}

.custom_item+.custom_item {
	border-top: 1px dashed #cdcdcd;
	margin-top: 20px;
}

.table_item {
	/deep/th {
		padding: 0;
	}

	.suffix {
		height: 30px;
		line-height: 28px;
	}

	/deep/.el-input__inner {
		border-radius: 4px 0 0 4px;
	}

	/deep/.el-input__icon {
		line-height: 30px;
	}
}

.suffix_input {
	/deep/.el-input__inner {
		border-radius: 4px 0 0 4px;
	}
}

.delete_btn {
	position: absolute;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
	width: 70px;
	border: 1px solid #ebeef5;
	border-left: none;
	background-color: #ffffff;
}

.tip {
	color: #999999;
	line-height: 35px;
}

.set_table {
	/deep/th {
		padding: 0;
	}

	/deep/.el-input__icon {
		line-height: 30px;
	}
}

.fix-footer-btns {
	.el-divider {
		background-color: #eeeeee;
		width: 95%;
		margin: 15px auto;
	}
}

.none1 {
	display: none;
}
</style>
  